package middleware

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"{{cookiecutter.app_name}}/common/errorx"
)

type JwtAdminMiddleware struct {
	Redis *redis.Redis
	APP   string
}

func NewJwtAdminMiddleware(Redis *redis.Redis, app string) *JwtAdminMiddleware {
	return &JwtAdminMiddleware{Redis: Redis, APP: app}
}

func (m *JwtAdminMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		logx.Info("admin中间件")
		id := r.Context().Value("userId").(string)
		token := r.Context().Value("token").(string)

		key := fmt.Sprintf("%v:admin:token:%v", m.APP, id)
		curToken, err := m.Redis.GetCtx(r.Context(), key)
		logx.Infof("curToken=%v", curToken)
		if err != nil || curToken != token {
			httpx.WriteJson(w, 401, errorx.NewCodeErrorNoMsg(401))
			return
		}
		next(w, r)
	}
}
